package org.gvp.record.service.impl;

import lombok.RequiredArgsConstructor;

import lombok.extern.log4j.Log4j2;
import org.gvp.common.cache.CacheHandler;
import org.gvp.record.dto.ItemDTO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.gvp.common.http.Page;
import org.gvp.record.service.ReportDetailService;
import org.gvp.record.repository.ReportDetailRepository;
import org.gvp.record.pojo.ReportDetail;
import java.util.List;
import java.util.Optional;

/**
 * 报销单详细信息表 服务层接口实现类
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class ReportDetailServiceImpl implements ReportDetailService {
    private final ReportDetailRepository reportDetailRepository;
    private final CacheHandler<Object> cacheHandler;
    /**
     * redis缓存key,报销单详选项数据
     */
    private final String REPORT_DETAIL_ITEM_KEY = "gvp:record:report_detail_item:";

    @Override
    public List<ItemDTO> findItemList() {
        log.debug("获取全部报销项选项列表");
        return this.cacheHandler.getList(REPORT_DETAIL_ITEM_KEY)
                .stream()
                .map(e -> e instanceof ItemDTO ? (ItemDTO)e : null)
                .toList();
    }

    @Override
    public boolean removeItem(String key) {
        log.debug("删除报销项目: {}", key);
        this.findItemList().stream()
                .filter(i -> i.getKey().equals(key))
                .findFirst().ifPresent(p -> {
            log.debug("找到报销项目: {}",p);
            this.cacheHandler.deleteFromList(REPORT_DETAIL_ITEM_KEY,p);
        });
        return true;
    }

    @Override
    public boolean editItem(ItemDTO dto) {
        // 获取全部
        // 找到指定的
        log.debug("更新报销项目选项: {}", dto);
        List<ItemDTO> itemList = this.findItemList();
        int index = 0;
        for (ItemDTO I : itemList){
            if (I.getKey().equals(dto.getKey())){
                break;
            }
            index ++ ;
        }
        log.debug("查找到需要更新的报销项目索引为: {}", index);
        this.cacheHandler.updateFromList(REPORT_DETAIL_ITEM_KEY,index,dto);
        return true;
    }

    @Override
    public boolean saveItem(ItemDTO dto) {
        log.debug("添加报销项目选项: {}", dto);
        cacheHandler.appendList(REPORT_DETAIL_ITEM_KEY,dto);
        return false;
    }

    @Override
    public int save(ReportDetail pojo) {
        log.debug("添加报销单详细信息表数据: {}",pojo);
        return this.reportDetailRepository.append(pojo);
    }

    @Override
    public ReportDetail saveAndReturn(ReportDetail pojo) {
        if (this.save(pojo) == 1){
            log.debug("添加并反回数据,执行添加成功");
            return this.findById(pojo.getId());
        }else {
            log.info("添加并反回数据,添加失败");
            return null;
        }
    }

    @Override
    public int removeById(Integer id) {
        log.debug("根据数据编号删除报销单详细信息表数据: {}",id);
        return this.reportDetailRepository.cancel(id);
    }

    @Override
    public int edit(ReportDetail pojo) {
        log.debug("更新报销单详细信息表数据,根据编号进行更新: {}",pojo);
        return this.reportDetailRepository.modify(pojo);
    }

    @Override
    public ReportDetail editAndReturn(ReportDetail pojo) {
        if (this.edit(pojo) == 1){
            log.debug("更新并反回数据执行更新成功");
            return this.findById(pojo.getId());
        }else {
            log.info("更新并反回数据执行更新失败");
            return null;
        }
    }

    @Override
    public ReportDetail findById(Integer id) {
        log.debug("使用报销单详细信息表数据编号查找数据: {}",id);
        return this.reportDetailRepository.searchById(id);
    }

    @Override
    public List<ReportDetail> findList() {
        log.debug("查找全部报销单详细信息表数据列表");
        return this.reportDetailRepository.searchList();
    }

    @Override
    public List<ReportDetail> findLimit(int start, int end) {
        log.debug("查找指定区间的报销单详细信息表数据列表: {}-{}",start,end);
        return this.reportDetailRepository.searchLimit(start,end);
    }

    @Override
    public Long findCount() {
        log.debug("查找全部数据量");
        return reportDetailRepository.searchCount("");
    }

    @Override
    public Page<ReportDetail> findPage(int currentPage, int pageSize) {
        log.debug("查找报销单详细信息表分页数据: 当前页={},页大小={}",currentPage,pageSize);
        return Page.<ReportDetail>builder()
                .total(this.findCount())
                .current(currentPage)
                .pageSize(pageSize)
                .build(this::findLimit);
    }

    @Override
    public List<ReportDetail> findListByReportId(Integer reportId, int page, int size) {
//        log.debug("根据报销单编号查找报销单详细信息数据: 报销单编号={},当前页={},页大小={}",reportId,page,size);
        return this.reportDetailRepository.searchListByReportId(reportId,page,size);
    }

    @Override
    public List<ReportDetail> findListByReportId(Integer reportId) {
        log.debug("根据报销单编号查找报销单详细信息数据: 报销单编号={}",reportId);
        return this.reportDetailRepository.searchListByReportId(reportId);
    }

    @Override
    public Page<ReportDetail> findPageByReportId(Integer reportId, int page, int size) {
        log.debug("根据报销单编号查找报销单详细信息分页数据: 报销单编号={},当前页={},页大小={}",reportId,page,size);
        Page<ReportDetail> pageData = Page.<ReportDetail>buildEmpty();
        Integer total = this.findCount().intValue();
        pageData.setTotal(total);
        pageData.setCurrentPage(page);
        pageData.setPageSize(size);
        int totalPage = total / size + 1;
        pageData.setTotalPage(totalPage);
        List<ReportDetail> listByReportId = this.findListByReportId(reportId, (page - 1) * size, size);
        pageData.setData(listByReportId);
        return pageData;
    }
}
